﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using DevExpress.Web.ASPxGridView;
using DevExpress.Web.ASPxEditors;
using Wilson.ORMapper;
using Touchmax;

public partial class InvoiceEdit : Page
{
    protected void page_Init(object sender, EventArgs e)
    {
        // this.txt_refNo.Text = "280674";
        if (!IsPostBack)
        {
            Session["InvEditWhere"] = null;// "DocNo='117710'";
            if (Request.QueryString["InvN"] != null && Request.QueryString["InvN"].ToString() != "0")
            {
                Session["InvEditWhere"] = "DocType = 'INVOICE' and DocNo=" + Request.QueryString["InvN"].ToString();
                this.dsInvoice.FilterExpression = "DocType = 'INVOICE' and DocNo=" + Request.QueryString["InvN"].ToString();
            }
            else if (Request.QueryString["InvN"] != null && Request.QueryString["InvN"].ToString() == "0")
            {
                if (Session["InvEditWhere"] == null)
                {
                    this.ASPxGridView1.AddNewRow();
                }
            }
        }
        if (Session["InvEditWhere"] != null)
        {
            this.dsInvoice.FilterExpression = Session["InvEditWhere"].ToString();
            if (this.ASPxGridView1.GetRow(0) != null)
                this.ASPxGridView1.StartEdit(0);
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
    }


    #region invoice
    protected void ASPxGridView1_Init(object sender, EventArgs e)
    {
        ASPxGridView grd = sender as ASPxGridView;
        if (grd != null)
            grd.ForceDataRowType(typeof(OpInvoice));
    }
    protected void ASPxGridView1_InitNewRow(object sender, DevExpress.Web.Data.ASPxDataInitNewRowEventArgs e)
    {
        e.NewValues["CustId"] = "0";
        e.NewValues["CustName"] = " ";
        if (Request.QueryString["sn"] != null)
        {
            string sn = Request.QueryString["sn"].ToString();
            e.NewValues["JobOrder"] = sn;
            string sql = "select custcode from xwjoborder where joborderno='" + sn + "'";
            string custId = SafeValue.SafeString(Touchmax.Manager.ORManager.ExecuteScalar(sql), "");
            sql = "select code from BoClient where custid='" + custId + "'";
            string custName = SafeValue.SafeString(Touchmax.Manager.ORManager.ExecuteScalar(sql), "");
            e.NewValues["CustId"] = custId;
            e.NewValues["CustName"] = custName;
            sql = "select BranchId from xwjoborder where joborderno='" + sn + "'";
            e.NewValues["BranchId"] = SafeValue.SafeString(Touchmax.Manager.ORManager.ExecuteScalar(sql), "");
        }
        e.NewValues["DocNo"] = "0";
        e.NewValues["DocDate"] = DateTime.Today;
        e.NewValues["Term"] = "CASH";
        string userId = HttpContext.Current.User.Identity.Name;
        e.NewValues["UserId"] = userId;
        e.NewValues["EntryDate"] = DateTime.Today;

    }
    protected void ASPxGridView1_CustomCallback(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewCustomCallbackEventArgs e)
    {
        ASPxTextBox invNCtr = this.ASPxGridView1.FindEditFormTemplateControl("txt_InvN") as ASPxTextBox;
        ASPxDateEdit invDate = this.ASPxGridView1.FindEditFormTemplateControl("date_InvD") as ASPxDateEdit;
        ASPxTextBox jobOrder = this.ASPxGridView1.FindEditFormTemplateControl("txt_JobOrder") as ASPxTextBox;
        ASPxTextBox custId = this.ASPxGridView1.FindEditFormTemplateControl("txt_CustId") as ASPxTextBox;
        ASPxTextBox branchId = this.ASPxGridView1.FindEditFormTemplateControl("txt_BranchId") as ASPxTextBox;

        ASPxTextBox term = this.ASPxGridView1.FindEditFormTemplateControl("txt_Term") as ASPxTextBox;
        ASPxTextBox rmk = this.ASPxGridView1.FindEditFormTemplateControl("txt_Rmk") as ASPxTextBox;

        string userName = HttpContext.Current.User.Identity.Name;
        string invN = GetNo("Invoice");
        if (invN.Length > 0)
        {
            OPathQuery query = new OPathQuery(typeof(Touchmax.OpInvoice), "DocNo='" + invN + "'");
            OpInvoice inv = Manager.ORManager.GetObject(query) as OpInvoice;
            bool isNew = false;
            if (invNCtr.Text.Length <2)// first insert invoice
            {
                isNew = true;
                inv = new OpInvoice();
                inv.DocNo = invN;
                inv.UserId = userName;
                inv.DocType = "INVOICE";
                inv.CustId = custId.Text;
                inv.BranchId = branchId.Text;
                inv.JobOrder = jobOrder.Text;
                inv.DocDate = invDate.Date;
                inv.DocNo = invN.ToString();
            }
            if (inv != null)
            {
                inv.Term = term.Text;
                inv.Remark = rmk.Text;
                try
                {
                    if (isNew)
                    {
                        Manager.ORManager.StartTracking(inv, Wilson.ORMapper.InitialState.Inserted);
                        Manager.ORManager.PersistChanges(inv);
                        SetNo(invN, "Invoice");
                    }
                    else
                    {
                        Manager.ORManager.StartTracking(inv, Wilson.ORMapper.InitialState.Updated);
                        Manager.ORManager.PersistChanges(inv);
                    }
                }
                catch
                {
                }
                Session["InvEditWhere"] = "DocType = 'INVOICE' and DocNo='" + invN + "'";
                this.dsInvoice.FilterExpression = "DocType = 'INVOICE' and DocNo='" + invN + "'";
                if (this.ASPxGridView1.GetRow(0) != null)
                    this.ASPxGridView1.StartEdit(0);
            }
        }
        else
        {
            throw new Exception("Save Failure,pls try again!");
        }
    }

    #endregion

    protected void ASPxGridView1_HtmlEditFormCreated(object sender, ASPxGridViewEditFormEventArgs e)
    {
        ASPxTextBox jobOrder = this.ASPxGridView1.FindEditFormTemplateControl("txt_JobOrder") as ASPxTextBox;
        if (jobOrder != null)
        {
            this.dsVehicle.FilterExpression = "JobOrder='" + jobOrder.Text + "'";
        }
    }

    #region invoice det
    protected void grid_InvDet_Init(object sender, EventArgs e)
    {
        ASPxGridView grd = sender as ASPxGridView;
        if (grd != null)
            grd.ForceDataRowType(typeof(OpInvoiceDet));
    }
    protected void grid_InvDet_BeforePerformDataSelect(object sender, EventArgs e)
    {
        ASPxGridView grd = (sender as ASPxGridView) as ASPxGridView;
        string sql = "select docNo from opinvoice where sequenceid=" + SafeValue.SafeInt(grd.GetMasterRowKeyValue(), 0);
        this.dsInvoiceDet.FilterExpression = "DocNo='" + SafeValue.SafeString(Touchmax.Manager.ORManager.ExecuteScalar(sql), "") + "'";
    }
    protected void grid_InvDet_InitNewRow(object sender, DevExpress.Web.Data.ASPxDataInitNewRowEventArgs e)
    {
        e.NewValues["DocLineNo"] = 0;
        e.NewValues["TotAmt"] = 0;
    }
    protected void grid_InvDet_RowUpdating(object sender, DevExpress.Web.Data.ASPxDataUpdatingEventArgs e)
    {
        ASPxGridView grd = sender as ASPxGridView;
        ASPxSpinEdit item = grd.FindEditFormTemplateControl("spin_det_ItemId") as ASPxSpinEdit;

        e.NewValues["ItemId"] = SafeValue.SafeInt(item.Value, 0);
    }
    protected void grid_InvDet_RowInserting(object sender, DevExpress.Web.Data.ASPxDataInsertingEventArgs e)
    {
        ASPxTextBox invNCtr = this.ASPxGridView1.FindEditFormTemplateControl("txt_InvN") as ASPxTextBox;
        string docNo = invNCtr.Text;
        string sql = "select max(DocLineNo) from opinvoicedet where docno='" + invNCtr.Text + "'";
        int lineN = SafeValue.SafeInt(Touchmax.Manager.ORManager.ExecuteScalar(sql), 0) + 1;

        if (invNCtr.Text.Length < 1)
        {
            e.Cancel = true;
        }
        else
        {
            e.NewValues["DocNo"] = invNCtr.Text;
            e.NewValues["DocLineNo"] = lineN;
            ASPxGridView grd = sender as ASPxGridView;
            ASPxSpinEdit item = grd.FindEditFormTemplateControl("spin_det_ItemId") as ASPxSpinEdit;

            e.NewValues["ItemId"] = SafeValue.SafeInt(item.Value, 0);
        }
    }
    protected void grid_InvDet_RowDeleting(object sender, DevExpress.Web.Data.ASPxDataDeletingEventArgs e)
    {
    }

    #endregion
    private string GetNo(string noType)
    {
        string sql = "select Counter from XXSetup where Category='" + noType + "'";
        int cnt = SafeValue.SafeInt(Touchmax.Manager.ORManager.ExecuteScalar(sql), 0) + 1;

        return cnt.ToString();

    }
    private void SetNo(string no, string noType)
    {
        string sql = string.Format("update XXSetup set counter='{0}' where category='{1}'", no, noType);
        int res = Touchmax.Manager.ORManager.ExecuteCommand(sql);
    }
    #region select 
    protected void gridPopCont_CustomJSProperties(object sender, ASPxGridViewClientJSPropertiesEventArgs e)
    {
        ASPxGridView grid = sender as ASPxGridView;
        object[] branchs = new object[grid.VisibleRowCount];
        object[] keyValues = new object[grid.VisibleRowCount];;
        for (int i = 0; i < grid.VisibleRowCount; i++)
        {
            keyValues[i] = grid.GetRowValues(i, "ChgcodeId");
            branchs[i] = grid.GetRowValues(i, "RetailRate");
        }
        e.Properties["cpAmt"] = branchs;
        e.Properties["cpKeyValues"] = keyValues;
    }
    protected void gridPopCont1_CustomJSProperties(object sender, ASPxGridViewClientJSPropertiesEventArgs e)
    {
        ASPxGridView grid = sender as ASPxGridView;
        object[] keyValues = new object[grid.VisibleRowCount];
        object[] vehicleNos = new object[grid.VisibleRowCount];
        for (int i = 0; i < grid.VisibleRowCount; i++)
        {
            vehicleNos[i] = grid.GetRowValues(i, "VehicleNo");
            keyValues[i] = grid.GetRowValues(i, "SequenceId");
        }
        e.Properties["cpVehicleNo"] = vehicleNos;
        e.Properties["cpKeyValues"] = keyValues;
    }
    #endregion


}
